package com.roc.rocketmqconsumer.messageType;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 单向消息-消费者
 *
 * @author Roker
 * @date 2025/07/06
 */
public class OneWayMsgConsumer {
    public static void main(String[] args) throws Exception {
        // 实例化消费者，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("roc_consumer_group");
        // 设置 NameServer 地址
        consumer.setNamesrvAddr("127.0.0.1:9876");
        // 订阅 Topic 和 Tag
        consumer.subscribe("TOPIC_ONEWAY", "*");

        // 注册消息监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    try {
                        String msgBody = new String(msg.getBody(), "UTF-8");
                        System.out.println("接收到单向消息：" + msgBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 启动消费者
        consumer.start();
        System.err.println("单向消息消费者已启动……");
    }
}